#-*- coding:UTF-8 -*-
"""
Copyright 2009 http://code.google.com/p/picinmht/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/picinmht/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from urlparse import urlparse
import os
import logging

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors

import util
from model import *

LastModified="Tue, 30 Mar 2009 00:00:00 GMT" 

class ShowPic(webapp.RequestHandler):
    """
    """
    def post(self,id):
        self.get(id)
                
    def get(self,id):
        logged,session=util.isLogin(self)
        if session is not None:
            username = session.name
        if not logged:
            self.redirect("/")
        user=util.getUserByName(username)
        
        id=int(id)
        template_values = {"pid":id}
        path = os.path.join(os.path.dirname(__file__), 'templates/pic/show.html')
        self.response.out.write(template.render(path,template_values ))

class GetPic(webapp.RequestHandler):
    def post(self,id):
        self.get(id)
    def get(self,id):
        logged,session=util.isLogin(self)
        if session is not None:
            username = session.name
        if not logged:
            self.redirect("/")
        user=util.getUserByName(username)
        id=int(id)
        etag="picinmhtpicid%d"%id
        match=self.request.headers.get("If-None-Match")
        if match and match==etag:
            self.response.set_status(304)
            return
        image=util.getPicture(id)
        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control']="max-age=315360000"
        self.response.headers['Last-Modified']=LastModified
        self.response.headers['ETag']=etag
        self.response.out.write(image.image)

class ListPic(webapp.RequestHandler):
    def post(self,mhtid):
        self.get(mhtid)
    def get(self,mhtid):
        logged,session=util.isLogin(self)
        if session is not None:
            username = session.name
        if not logged:
            self.redirect("/")
        user=util.getUserByName(username)
            
        mhtid=int(mhtid)
        query=db.GqlQuery ("SELECT * FROM MhtFile WHERE mhtid=:1",mhtid)
        msg=""
        images=[]
        template_values={}
        found=False
        for mht in query:
            found=True
            query=db.GqlQuery ("SELECT * FROM Image WHERE mhtid=:1 ORDER BY picid",mhtid)
            for img in query:
                images.append(img.picid)   
        if found:
            template_values["mhtname"]=mht.name
        else:
            template_values["mhtname"]="NOT FOUND"
            msg="mht does not exist"
        template_values["images"]=images
        referer=self.request.headers.get('Referer',"/mht/list")
        refererurl=urlparse(referer)[2]
        if urlparse(referer)[4]!="":
            refererurl+="?"+urlparse(referer)[4]
        template_values["referer"]=refererurl
        template_values["msg"]=msg
        if user:
            template_values["username"]=user.name
        path = os.path.join(os.path.dirname(__file__), 'templates/pic/list.html')
        self.response.out.write(template.render(path,template_values ))
        
class DeletePic(webapp.RequestHandler):
    def post(self):
        logged,session=util.isLogin(self)
        if session is not None:
            username = session.name
        if not logged:
            self.redirect("/")
        user=util.getUserByName(username)
        referer=self.request.get('referer',"/mht/list")        
        picids=self.request.get_all("picid")
        logging.info("deleting...%s"%",".join(picids))
        if len(picids)==0:
            self.redirect(referer)
        else:
            logging.info("SELECT * FROM Image WHERE picid in (%s)"%",".join(picids))
            query=db.GqlQuery ("SELECT * FROM Image WHERE picid in (%s)"%",".join(picids))
            for pic in query:
                user.byteused-=len(pic.image)
                pic.delete()
                sysinfo=util.getSysInfo()
                sysinfo.picnum=sysinfo.picnum-1
                sysinfo.put()
                try:
                    r=memcache.set("SysInfo_",sysinfo)
                    if not r:
                        logging.error("Memcache set sysinfo failed.")
                except apiproxy_errors.OverQuotaError, message:
                    logging.error(message)
            user.put()
            try:
                r=memcache.set("userbyid_%d"%userid,user)
                if not r:
                    logging.error("Memcache set sysinfo failed.")
            except apiproxy_errors.OverQuotaError, message:
                logging.error(message)
            self.redirect(referer)
        
    def get(self):
        logged,session=util.isLogin(self)
        if session is not None:
            username = session.name
        if not logged:
            self.redirect("/")
        user=util.getUserByName(username)
        
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'templates/pic/list.html')
        self.response.out.write(template.render(path,template_values ))
        
def main():
    application = webapp.WSGIApplication([
                                          ('/pic/list/(\d+)',ListPic),
                                          ('/pic/show/(\d+)',ShowPic),
                                          ('/pic/get/(\d+)',GetPic),
                                          ('/pic/delete',DeletePic)
                                          ],debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()